package com.example.ivideo_2211a.fabu

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.ivideo_2211a.R

class VideoListAdapter(
    private val onCheckedChange: (VideoFaEntityItem, Boolean) -> Unit,
    private val onItemClick: (VideoFaEntityItem) -> Unit
) : RecyclerView.Adapter<VideoListAdapter.VideoViewHolder>() {
    private val data = mutableListOf<VideoFaEntityItem>()
    private val checkedSet = mutableSetOf<Int>()

    fun clearSelection() {
        checkedSet.clear()
        notifyDataSetChanged()
    }

    fun submitList(list: List<VideoFaEntityItem>) {
        data.clear()
        data.addAll(list)
        notifyDataSetChanged()
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VideoViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_video_select, parent, false)
        return VideoViewHolder(view)
    }

    override fun onBindViewHolder(holder: VideoViewHolder, position: Int) {
        val item = data[position]
        holder.bind(item, checkedSet.contains(item.videoId))
        holder.checkBox.setOnCheckedChangeListener(null)
        holder.checkBox.isChecked = checkedSet.contains(item.videoId)
        holder.checkBox.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) checkedSet.add(item.videoId) else checkedSet.remove(item.videoId)
            onCheckedChange(item, isChecked)
        }
        
        // 设置列表项点击事件
        holder.itemView.setOnClickListener {
            onItemClick(item)
        }
    }

    override fun getItemCount() = data.size

    class VideoViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val checkBox: CheckBox = view.findViewById(R.id.checkbox)
        private val title: TextView = view.findViewById(R.id.title)
        private val cover: ImageView = view.findViewById(R.id.cover)
        fun bind(item: VideoFaEntityItem, checked: Boolean) {
            title.text = item.title
            checkBox.isChecked = checked
            Glide.with(cover).load(item.videoUrl).into(cover)
        }
    }
}
